package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addCategory(@RequestBody Category category, HttpSession session){
/*        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        Long id = (Long) session.getAttribute("employee");
        category.setCreateUser(id);
        category.setUpdateUser(id);*/

        boolean save = categoryService.save(category);

        return save? R.success("添加成功"): R.error("添加失败");
    }

    @GetMapping("/page")
    public R<Page> selectPage(int page, int pageSize){

        Page pageInfo = new Page(page,pageSize);

        categoryService.page(pageInfo);

        return R.success(pageInfo);
    }

    @DeleteMapping
    public R deleteCategory(Long id){

        R r = categoryService.deleteById(id);

        return r;
    }

    @PutMapping
    public R updateCategory(@RequestBody Category category,HttpSession session){
/*        category.setUpdateTime(LocalDateTime.now());

        Long id = (Long) session.getAttribute("employee");
        category.setUpdateUser(id);*/

        boolean b = categoryService.updateById(category);

        return b? R.success("修改成功"): R.error("修改失败");
    }

    @GetMapping("/list")
    public R selectByType(Integer type){

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(type!=null,Category::getType,type);
        qw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(qw);

        return R.success(list);

    }
}
